#include "StdAfx.h"
#include "NetOperation.h"

#include "asyntcpserver.h"
#include <iostream>


CAsynTcpServer * CAsynTcpServer::m_pAsynTcpServer = NULL;

CAsynTcpServer::CAsynTcpServer(int iPort)
:CThread()
,m_iPort(iPort)
{
}

CAsynTcpServer::~CAsynTcpServer(void)
{
}

CAsynTcpServer * CAsynTcpServer::GetInstance(int iPort)
{
	if (NULL == m_pAsynTcpServer)
	{
		m_pAsynTcpServer = new CAsynTcpServer(iPort);
	}
	return m_pAsynTcpServer;
}

LPVOID CAsynTcpServer::OnRun()
{
	if (!m_TcpServer.Init(m_iPort))
	{
		return NULL;
	}
	CTcpClient *pTcpClient = NULL;
	for (;;)
	{
		if (NULL == pTcpClient)
		{
			pTcpClient = m_TcpServer.Accept();
			if (NULL == pTcpClient)
			{
				continue;
			}
			pTcpClient->SetNoBlock(true);
		}
		char pBuf[1024] = {0};
		int iRead = pTcpClient->ReadData(pBuf,1024,1);
		if (iRead == 0)
		{
			continue;
		}
		else if (iRead < 0)
		{
			break;
		}
		std::cout<<"Recv["<<iRead<<"]Byte From "<<pTcpClient->GetClientIP()<<":" <<pBuf<<std::endl;
	}
	if (NULL != pTcpClient)
	{
		delete pTcpClient;
		pTcpClient = NULL;
	}
	return NULL;
}
